import random
import re

from django.contrib.auth.hashers import make_password
from django.http import HttpResponse
from rest_framework.response import Response
from rest_framework.views import APIView

from users.ser import *
from utils.comm import send_message, get_redis
from users.models import *


# 测试
class Text(APIView):
    def get(self, request):
        conn = get_redis()
        conn.setex('username', 10, 'xiaoming236')
        name = conn.get('username')
        return Response(name)


# 注册
class Register(APIView):
    def post(self, request):

        # 用户名
        username = request.data.get('username')
        if not username:
            return Response({'code': 10010})
        # 格式是否正确
        name = re.match('\w{5,10}$', username)
        if not name:
            return Response({'code': 10011})
        # 是否唯一
        user = User.objects.filter(username=username).first()
        if user:
            return Response({'code': 10012})

        # 密码
        password = request.data.get('password')
        if not password:
            return Response({'code': 10013})
        # 格式是否正确
        pwd = re.match('\w{3,6}$', password)
        if not pwd:
            return Response({'code': 10014})

        # 手机号
        mobile = request.data.get('mobile')
        if not mobile:
            return Response({'code': 10016})
        phone = re.match('^1[3-9]\d{9}$', mobile)
        if not phone:
            return Response({'code': 10017})
        # 是否唯一
        sloe = User.objects.filter(mobile=mobile).first()
        if sloe:
            return Response({'code': 10018})

        # 验证码验证
        smscode = request.data.get('smscode')
        conn = get_redis()
        code = conn.get(mobile)
        if code:
            code = str(code, encoding='utf8')
        if smscode != code:
            return Response({'code': 10019})

        return Response({'code': 200, 'meg': '注册成功'})


# 验证码
class SendSms(APIView):
    def post(self, request):
        mobile = request.data.get('mobile')
        # 验证图片验证码,通过后发短信
        uid = request.data.get('uid')
        imagecode = request.data.get('imagecode')
        conn = get_redis()
        imgcode = conn.get(uid)
        if imgcode:
            imgcode = str(imgcode, encoding='utf8')
            if imagecode.lower() == imgcode.lower():
                codesms = random.randint(1000, 9999)
                res = send_message(mobile, str(codesms), 1)
                if res:
                    # 发生成功后存入redis
                    conn = get_redis()
                    conn.setex(mobile, 60, codesms)
                    # 判断是否同意协议
                    agree = request.data.get('agree')
                    if not agree:
                        return Response({'code': 10020})
                    # 注册功能
                    request.data['password'] = make_password(request.data.get('password'))
                    ser = UserModel(data=request.data)
                    if ser.is_valid():
                        ser.save()
                        return Response({'code': 200})
                    return Response({'code': 10021})


# 生成图片验证码
from utils.captcha.captcha import captcha


class CreateCaptcha(APIView):
    def get(self, request):
        uuid = request.GET.get('uuid')
        name, text, img = captcha.generate_captcha()
        # redis存储
        conn = get_redis()
        conn.set(uuid, text)
        return HttpResponse(img, content_type='image/jpg')


# 添加地址
class AddressM(APIView):
    def post(self, request):
        ser = Address(data=request.data)
        if ser.is_valid():
            ser.save()
            return Response({'code': 200})

    def get(self, request):
        userid = request.GET.get('userid')
        address = Address.objects.filter(user_id=userid).all()
        ser = Address(address, many=True)
        return Response({'code': 200, 'list': ser.data})

    def put(self, request):
        # 获取id
        id = request.GET.get('id')
        # 通过id查询
        address = Address.objects.filter(id=id).first()
        # 根据userid和is_default=1更新is_default=0
        Address.objects.filter(user_id=address.user_id, is_default=1).update(is_default=0)
        # 把当前id设置成默认5
        address.is_default = 1
        address.save()
        return Response({"code": 200})